package buildings.net.server.parallel;

import buildings.Building;
import buildings.dwelling.Dwelling;
import buildings.dwelling.hotel.Hotel;
import buildings.net.server.exceptions.BuildingUnderArrestException;
import buildings.office.OfficeBuilding;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class SerialServerThread extends Thread {

    private Socket clientSocket;

    public SerialServerThread(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    @Override
    public void run() {
        try {
            ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
            ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
            out.writeObject("HELLO");
            Building buf = null;
            float cost = 0;
            String type = null;
            String str = null;
            while (true) {

                //определяем, что хочет передать клиент
                type = in.readUTF();

                //если клиент прощается, завершаем прием
                if (type.equals("end")) {
                    break;
                }

                //получаем здание
                try {
                    buf = (Building) in.readObject();
                } catch (ClassNotFoundException e) {
                    break;
                }

                //оцениваем здание
                try {
                    str = Float.toString(getCost((Dwelling) buf));
                } catch (BuildingUnderArrestException e) {
                    str = "Здание под арестом!";
                }

                out.writeObject(str);
            }
        } catch (IOException e) {
        }
    }

    private static float getCost(Building b)
            throws BuildingUnderArrestException {
        if (!isArested()) {
            if (b instanceof Dwelling) {
                return b.getTotalSquare() * 1000;
            }
            if (b instanceof OfficeBuilding) {
                return b.getTotalSquare() * 1500;
            }
            if (b instanceof Hotel) {
                return b.getTotalSquare() * 2000;
            }
        }
        throw new BuildingUnderArrestException();
    }

    private static boolean isArested() {
        Random r = new Random();
        int buf = r.nextInt(100);
        if (buf < 10) {
            return true;
        }
        return false;
    }
}
